package com.antrain.adms.controller;

import java.time.LocalDateTime;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import com.antrain.adms.pojo.User;
import com.antrain.adms.service.IUserService;
import com.antrain.adms.utils.CommonResult;
import com.antrain.adms.utils.JwtUtil;
import com.antrain.adms.utils.ShaUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
  @Resource
  private IUserService userService;

  @PostMapping("/login")
  public CommonResult login(@RequestBody Map<String,Object> param){
    System.out.println(param);
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("telephone", param.get("telephone")).eq("password", ShaUtil.getSHA256(param.get("password").toString()));
    User user =  userService.getOne(wrapper);
    if (user == null){
      return CommonResult.failed("手机号或密码错误");
    }
    user.setLastLogin(LocalDateTime.now());
    updateLoginTime(user.getId());
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("token", JwtUtil.create(user));
    jsonObject.put("id",user.getId());
    return CommonResult.success(jsonObject);
  }

  private void updateLoginTime(int id){
    User user = new User();
    user.setId(id);
    user.setLastLogin(LocalDateTime.now());
    userService.updateById(user);
  }
}
